import vue from '@vitejs/plugin-vue';
import path from 'path';
import AutoImport from 'unplugin-auto-import/vite';
import IconsResolver from 'unplugin-icons/resolver'; // 自动注册图标组件
import Icons from 'unplugin-icons/vite'; // 自动注册图标组件
import { AntDesignVueResolver, ElementPlusResolver } from 'unplugin-vue-components/resolvers'; // 自动注册组件
import Components from 'unplugin-vue-components/vite';
import { ConfigEnv, loadEnv, UserConfig } from 'vite';
import VueDevTools from 'vite-plugin-vue-devtools'; // vue 调试工具

const CWD = process.cwd();

export default ({ mode }: ConfigEnv): UserConfig => {
  // 获取环境变量
  const { VITE_BASE_URL, VITE_API_URL_PREFIX } = loadEnv(mode, CWD);
  return {
    base: VITE_BASE_URL,
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [
          ElementPlusResolver(),
          // 自动导入图标组件
          IconsResolver({
            prefix: 'Icon',
          }),
        ],
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          AntDesignVueResolver({
            importStyle: false, // css in js
          }),
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ['ep'],
          }),
        ],
      }),
      Icons({
        autoInstall: true,
      }),
      VueDevTools(),
    ],
    server: {
      port: 8888,
      host: true,
      open: true,
      proxy: {
        [VITE_API_URL_PREFIX]: {
          target: 'https://sn.zszhyl.com/bs_server',
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${VITE_API_URL_PREFIX}`), ''),
          bypass: (req, res, options: any) => {
            // 获取代理后的请求地址
            const proxyUrl = new URL(options.rewrite(req.url) || '', options.target as string)?.href || '';
            req.headers['x-req-proxyUrl'] = proxyUrl;
            res?.setHeader('x-res-proxyUrl', proxyUrl);
          },
        },
      },
    },
  };
};
